package com.idbk.chargestation.activity.pile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.adapter.PointDetailAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonPoint;
import com.idbk.chargestation.bean.JsonPointsOverview;
import com.idbk.chargestation.fragment.FragmentPiles;
import com.idbk.chargestation.fragment.FragmentPointDetail;
import com.idbk.chargestation.net.EEmptyHttpResponse;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.FlagRequest;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.util.OtherUtil;

/**
 * 充电点详情
 *
 * @author liangzw, lupc
 */
public class ActivityPointDetail extends BaseActivity implements OnClickListener {

    public static final int POINT_DETAIL = 0;
    public static final int POINT_PILES = 1;
    public static final int POINT_COMMENT = 2;
    private Context mContext;

    private TabLayout mTabLayout;//切换Tab

    private int mPointId;
    private JsonPoint mPointData;

    private PointDetailAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_point_detail);

        mContext = ActivityPointDetail.this;

        setupView();

        setupData();
    }

    private void setupView() {
        mPointId = getIntent().getIntExtra(Const.KEY_ID, -1);

        setupToolBar2();
        mToolbar2.getImageMenu1().setVisibility(View.VISIBLE);
        mToolbar2.getImageMenu1().setOnClickListener(this);
        mToolbar2.getImageMenu2().setVisibility(View.VISIBLE);
        mToolbar2.getImageMenu2().setImageResource(R.drawable.btn_map_share_normal);
        mToolbar2.getImageMenu2().setOnClickListener(this);


        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        ViewPager mViewPager = (ViewPager) findViewById(R.id.charge_point_pager);
        mAdapter = new PointDetailAdapter(getSupportFragmentManager(), mPointId, 0, 0);
        //设置Tab模式
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        //为TabLayout添加Tab名称
        mTabLayout.addTab(mTabLayout.newTab().setText("详情"));
        mTabLayout.addTab(mTabLayout.newTab().setText("电桩"));
        mTabLayout.addTab(mTabLayout.newTab().setText("评论"));
        if (mViewPager != null) {
            //ViewPager加载适配器
            mViewPager.setAdapter(mAdapter);
            //TabLayout加载ViewPager
            mTabLayout.setupWithViewPager(mViewPager);
            mViewPager.setOffscreenPageLimit(3);//限制预加载3个Fragment
            int index = getIntent().getIntExtra(Const.POINT_DETAIL_INDEX, POINT_DETAIL);
            mViewPager.setCurrentItem(index);
        }
    }

    private void setupData() {
        showMyProgressDialog(true, true, "加载中...");
        //请求充电点详情数据
        mMainRequest = ChargeStationAPI.getPointDetail(mPointId, mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonPoint result = GsonUtils.toBean(JsonPoint.class, response);
            if (handleResponseStatus(result)) {
                //绑定数据
                bindView(result);
                FragmentPointDetail f0 = (FragmentPointDetail) mAdapter.getItem(0);
                f0.notifyDataCallback(result);

                //电桩
                FragmentPiles f1 = (FragmentPiles) mAdapter.getItem(1);
                f1.notifyDataCallback(result);
            } else {
                Toast.makeText(mContext, "数据错误！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext,
                    R.string.common_tip_resultfail,
                    Toast.LENGTH_SHORT).show();
            finish();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }

    };

    private void bindView(JsonPoint data) {
        mPointData = data;

        if (data.isCollection) {
            mToolbar2.getImageMenu1().setImageResource(R.drawable.btn_map_favorite_active);
        } else {
            mToolbar2.getImageMenu1().setImageResource(R.drawable.btn_map_favorite_normal);
        }

        setPileCount(data.total, data.idleNum);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FlagRequest.REQUEST_RESERVE_PILE &&
                resultCode == Activity.RESULT_OK) {
            //表示预约成功，需要刷新电桩列表
            setupData();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void collectionPoint() {
        if (mPointData == null) {
            return;
        }
        //检查是否登录
        if (!checkLogin(true)) {
            return;
        }

        if (mPointData.isCollection) {
            ChargeStationAPI.cancelCollectPoint(mPointData.id, new EEmptyHttpResponse());
            mToolbar2.getImageMenu1().setImageResource(R.drawable.btn_map_favorite_normal);
        } else {
            ChargeStationAPI.collectPoint(mPointData.id, new EEmptyHttpResponse());
            mToolbar2.getImageMenu1().setImageResource(R.drawable.btn_map_favorite_active);
        }
        mPointData.isCollection = !mPointData.isCollection;
        Intent intent = new Intent();
        intent.putExtra(JsonPointsOverview.KEY, mPointData);
        setResult(RESULT_OK, intent);
    }

    /**
     * 更新评论总数
     *
     * @param count 数量
     */
    public void setCommentCount(int count) {
        mTabLayout.getTabAt(2).setText(PointDetailAdapter.getCompactNumberTitle("评论", count));
    }

    public void setPileCount(int total, int idleCount) {
        mTabLayout.getTabAt(1).setText(PointDetailAdapter.getCompactNumberTitle("电桩", total, idleCount));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.imageview_menu_1) {
            collectionPoint();
        } else if (v.getId() == R.id.imageview_menu_2) {
            OtherUtil.share(mContext, mPointId, mPointData.name);
        }
    }

}